var systemId = 2214;
var systemtext ="云健康 . 处方点评系统";

var yiyuanId ;//= JSON.parse($.cookie("parameterArray"))[0].bck01;

var TitleType = 1; //系统头类别号，自定义 0 是统计分析，1是其他
/*$(function(){
});*/
$(document).ready(function(){
	mainInt();
	addHospitalEvent();
})

var isleave = true;
window.onfocus = function(){
	if(isleave){
		checkUserId();
	}
	isleave = true;
}
document.addEventListener("visibilitychange", function(){
	isleave = false;
	checkUserId();
});

	
function checkUserId(){
	var unique_user_code = $("#unique_user_code").attr("data-id");
	$.ajax({
        dataType: "jsonp",
        type: 'get',
        url:  centerUrl+"/sysUser/getUserCode",
        async: false,
        success: function (data) {
        	if(data){
        		
        		if(unique_user_code !=data){
        			layer.confirm('登录名不一致，请重新登陆！', {
        				btn: ['确定'], //按钮
        				closeBtn:0,
        				shade: 0.3,
        			}, function(){
        				isleave= false;
        				if(fromMain&&"1"==fromMain){
        					window.location.href= $.cookie('unityUrl');
        				}else{
        					window.location.href = base;
        				}
        				layer.closeAll();
        				
        			})
        		}
        	}
        }
    });
}
	

 window.onbeforeunload = function(){
	 if(isleave){
		 
		 return '您确定要离开云健康吗？';
	 }
 };


  window.onunload = function(){
//	    clearMq();
	};
	function clearMq(){
	    $.ajax({
	        dataType: "jsonp",
	        crossDomain: true,
	        jsonp: "callback",
	        jsonpCallback: "success_jsonp",
	        type: 'get',
	        data: {
	        	 jsessionids:jsessionids
	        },
	        timeout : 1000, //超时
	        url:  mqUrl+"/Mq/MQ/deleteTopicUser?selectName=" + selectName,
	        async: true,
	        success: function (data) {

	        }
	    });
	};

function mainInt()
{
	if(userId==null ||userId==undefined){
//		if($.cookie('userId')==null ||$.cookie('userId')==undefined){
		window.location.href = host;
		return false;
	}
	datas.getMainHeaderData();
	views.header.init($('header'));
	views.nav.init($('.content-nav'));
}
	
/*消息订阅与发送*/
;(function ($) {
    'use strict';
    $.gevent = (function () {
        var subscribeEvent, publishEvent, unsubscribeEvent,
            $customSubMap = {};
        publishEvent = function () {
            var arg_list = [],
                arg_count, event_name,
                event_obj, data, data_list;

            arg_list  = arg_list.slice.call( arguments, 0 );
            arg_count = arg_list.length;

            if ( arg_count === 0 ) { return false; }

            event_name = arg_list.shift();
            event_obj  = $customSubMap[ event_name ];

            if ( ! event_obj ) { return false; }

            if ( arg_count > 1 ) {
                data      = arg_list.shift();
                data_list = $.isArray( data ) ? data : [ data ];
            }
            else {
                data_list = [];
            }

            event_obj.trigger( event_name, data_list );
            return true;
        };
        subscribeEvent = function ( $collection, event_name, fn ) {
            $collection.on( event_name, fn );

            if ( $customSubMap[ event_name ] ) {
                $customSubMap[ event_name ]
                    = $customSubMap[ event_name ].add( $collection );
            }
            else {
                $customSubMap[ event_name ] = $collection;
            }
        };
        unsubscribeEvent = function ( $collection, event_name ) {
            if ( ! $customSubMap[ event_name ] ){ return false; }

            $customSubMap[ event_name ]
                = $customSubMap[ event_name ].not( $collection );

            if ( $customSubMap[ event_name ].length === 0 ){
                delete $customSubMap[ event_name ];
            }

            return true;
        };
        console.log($.gevent);
        return {
            publish     : publishEvent,
            subscribe   : subscribeEvent,
            unsubscribe : unsubscribeEvent
        };
    }());
}( jQuery ));
var datas = (function () {
    'use strict';
    var getDataByAjax,
        getMainHeaderData,
        getMainNavData;
    getDataByAjax = function (jsonObj){
        $.ajax({
            dataType: "jsonp",
//            crossDomain: true,
//            jsonp:"callback",
//            jsonpCallback:"success_jsonp",
            type:jsonObj.type||'get',
            data:jsonObj.param||{},
            url:jsonObj.url,
            async:true,
            success:function(data){
                jsonObj.successFn(data);
            }
        });
    };

    //获取头部数据
    getMainHeaderData = function () {
        getDataByAjax({
            type:'get',
            url:centerUrl+'/sysUser/getCloudOMenuByUserId',
            param: {
                'language':'zh-CN',
                'userId':userId,
//                'loginCode':$.cookie('loginName'),
                'loginCode':loginName,
                'sysModId':systemId
            },
            successFn:function(data){
                console.log('页面头部数据--');
                console.log(data);
                $.gevent.publish('mainHeader-data-received',[{mainHeaderData:data}]);
            }
        });
        return this;
    };
    //获取左侧导航数据
   getMainNavData = function (obj) {
       getDataByAjax({
           type:'get',
           url:obj.url,
           param:{
               'language':'zh-CN',
               'userId':userId,
               'loginCode':loginName,
               'sysModId':systemId,
               'sysModSId':obj.id
           },
           successFn: function (data) {
        	   debugger;
               console.log('左侧导航数据--');
               console.log(data);
               if(TitleType == 0){//TitleType 为0 是报表
            	   if(data.length > 0){
            		   var list = [];
            		   for(var i=0;i<data.length;i++){
            			   list = list.concat(data[i].childList);
            		   }
            		   $.gevent.publish('mainNav-data-received',[{mainNavData:list}]);
            	   }
            	   
               }else {
            	   $.gevent.publish('mainNav-data-received',[{mainNavData:data}]);
               }
           },error : function(XMLHttpRequest, textStatus, errorThrown) {
        	   console.log(errorThrown);
           }
           
       });
       return this;
   };
    return {
        getMainHeaderData:getMainHeaderData,
        getMainNavData:getMainNavData
    };
}());
/*页面中views*/
var views = (function(){
    'use strict';

    return {

    }
}())
/*页面头部导航*/
views.header = (function(){
    'use strict';
    var
        configMap = {
            main_html:String()+
                 '<div id="banner" class="inline">'+
                        '<div class="inline logo" ></div><div class="inline systemText">'+systemtext+'</div>'+
                    '</div>'+
                '<div class="inline" id="minMenu">'+
                    '<ul class="list-unstyle list-inline"></ul>'+
                '</div>'+
                '<div class="left_info">'+
                '<div id="admin">'+
	                '<div class="btn-group skin-change admin">'+
	                '<div class="btn dropdown-toggle" data-toggle="dropdown">更换皮肤<span class="caret"></span></div>'+
		                '<ul class="dropdown-menu">'+
		                	'<li class="skinList" id="skin1">光鲜绿</li>'+
		                	'<li class="skinList" id="skin2">深海蓝</li>'+
		            	'</ul>'+
		            '</div>'+
                    '<label class="admin" id="changeDh" onclick="changeHeader()">'+
                        '<div class="inline adminImg"></div> 简约导航'+
                    '</label>'+
                    '<label class="admin" onclick="userInfoEvent()">'+
                    	'<div class="inline adminImg"></div> '+trueName+
                    	'<div type="hidden" data-id='+userId+ ' id="unique_user_code"></div>'+
                    '</label>'+
                    '<label class="admin" onclick="logout()">'+
                        '<div class="inline adminImg"></div> 退出'+
                    '</label>'+
                '</div>'+
                '<div class="left_self"><span class="name">所属医院:</span><select id="hospital" onchange="changeHospitalEvent();"></select></div>'+
                '</div>',
            srcImg:[

            ],
        },
        stateMap = {},
        jqueryMap = {},
        setJqueryMap,setDomEvent,handleData,
        configModule,init;
    setJqueryMap = function(){
        var $c = stateMap.$append_target;
        jqueryMap = {
            $container:$c,
            $menuUl:$c.find('#minMenu ul'),
            $exitBtn:$c.find('.exit'),
        };
        setDomEvent();
    };
    setDomEvent = function(){
        $.gevent.subscribe(jqueryMap.$menuUl,'mainHeader-data-received', function (e,msg) {
            var d = msg.mainHeaderData;
            var str = '';
            configModule(d);
            for(var i= 0,len= d.length;i<len;i++){
            	str += '<li class="header">'+
                '<a id="'+d[i].id+'">' +
                    '<span><span class="headerbg'+d[i].id+'"></span>'+d[i].text+'</span>'+
                '</a>'+
            '</li>';
            }
            jqueryMap.$menuUl.html(str);
            /*默认加载第一项*/
            jqueryMap.$container.find('#minMenu a').first().trigger('click');
        });
       jqueryMap.$menuUl.on('click','a',function(){
    	   $("#tabContent").empty();
    	   var obj = {};
    	   var url;
           var id = $(this).attr('id');
           $(this).parent().addClass('checkMinMenu').siblings().removeClass('checkMinMenu');
           var flagtext = $(this).children().text().trim();
           var newBlock;
           if(flagtext == '统计分析'){
        	   $("#normal_content").hide();
        	   $("#down_content").show();
        	   $(".console-label").css({width:"180px"});
        	   $(".console-items-container").css({left:"180px"});
        	   url = centerUrl + "/sysReportView/getReportTree?userId="+userId+"&loginCode="+loginName;
        	   TitleType = 0;
           }
        else{ //其他
        	   $("#normal_content").hide();
        	   $("#down_content").show();
        	   $(".console-label").css({width:"180px"});
        	   $(".console-items-container").css({left:"180px"});
        	   url = centerUrl+'/sysUser/getCloudSMenuByUserId';
        	   TitleType = 1;
           }
           obj.id = id;
           obj.url = url;
           datas.getMainNavData(obj);
           refushPosition('001');
           var timer = setInterval(function()
        		   {
        	   		 if(newBlock)
        	   		 {
        	   			change_skin();
        	   			newBlock = null;
        	   			clearInterval(timer);
        	   		 }
        		   }, 50);
       });
        jqueryMap.$exitBtn.on('click',function(){
            window.location.href = host;
        });
    };
    handleData = function(){

    };
    configModule = function (d) {
        stateMap.mainHeaderData = d;
        handleData();
    };
    init = function($container){
        stateMap.$append_target = $container;
        $container.append(configMap.main_html);
        setJqueryMap();
        return this;
    };
    return {
        configModule:configModule,
        init:init
    }
}())
/*页面左侧导航*/
views.nav = (function(){
    'use strict';
    var
        configMap = {
            main_html:String()+
                '<div class="side-nav">'+
                    '<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"></div>'+
                '</div>',
        },
        stateMap = {
            $append_target:'',
            expanded:true
        },
        jqueryMap = {},
        setJqueryMap,setDomEvent,drawGroupView,navExpandToggle,
        configModule,init;
    setJqueryMap = function($c){
        jqueryMap = {
            $group: $c.find('#accordion'),
            $directionBtn:$c.find('#directionBtn'),
        };
        setDomEvent();
    };
    setDomEvent = function(){
        $.gevent.subscribe(jqueryMap.$group,'mainNav-data-received', function (e,msg) {
            var d = msg.mainNavData;
            configModule(msg);
            drawGroupView($(e.target));
        });
        jqueryMap.$group.on('show.bs.collapse','.panel-collapse', function () {
            $(this).parent().find('a span').removeClass('glyphicon-menu-right').addClass('glyphicon-menu-down');
        });
        jqueryMap.$group.on('hide.bs.collapse','.panel-collapse' ,function () {
            $(this).parent().find('a span').removeClass('glyphicon-menu-down').addClass('glyphicon-menu-right');
        });
        jqueryMap.$directionBtn.on('click', function () {
            navExpandToggle();
        });
        jqueryMap.$group.on('click','a[data-src]',function(){
        	var id = $(this).attr("data-id");
        	jqueryMap.$group.find('a[data-src]').parent().removeClass('active');
        	$(this).parent().addClass('active');
        	var thisUrl=$(this).attr("data-src");
        	if(TitleType == 0){
        		var html = "<iframe src='"+thisUrl+"' frameborder='0' allowtransparency='true' height='100%' width='100%'></iframe>";
        		$('#tabContent').empty().append(html);
        	}else{
        		$('#tabContent').load(thisUrl,function(responseTxt,statusTxt,xhr){
        			   if(statusTxt=="success"){
        				   if(loginName!="admin"){
        					   checkPermission(id,".set_container","list");
        	        		}
        			   }
        		 });
        	}
    		refushPosition('002');
        });
    };
   
    drawGroupView = function ($target) {
        jqueryMap.$group.empty();
        var currUrl = window.location.pathname;
        var currHref = currUrl.slice(12,currUrl.length);
        var d = stateMap.mainNavData;
        for(var i= 0,len= d.length;i<len;i++){
            var oDiv = $('<div class="panel panel-default"></div>');
            var str = String()+
                '<div class="panel-heading" role="tab">'+
                    '<h4 class="panel-title">'+
                        '<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse'+i+'" aria-expanded="false" aria-controls="#collapse'+i+'"> '+d[i].text+
                        '<span class="glyphicon glyphicon-menu-right pull-right"></span>'+
                        '</a>'+
                    '</h4>'+
                '</div>'+
                '<div id="collapse'+i+'" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading'+i+'">'+
                    '<div class="panel-body">'+
                        '<ul class="nav nav-pills nav-stacked"></ul>'+
                    '</div>'+
                '</div>';
            oDiv.html(str);
            $('#accordion').append(oDiv);
            if(d[i].children.length!=0){
                var dc = d[i].children;
                for(var j= 0,jLen=dc.length;j<jLen;j++){
                	if(TitleType == 0){
                		var oLi = $('<li role="tablink"><a href="javascript:void(0);" data-src="'+baobiaoUrl+'reportid='+dc[j].id+'&jsessionids='+$.cookie("jsessionids")+'">'+dc[j].text+'</a></li>');
                		
                	}else{
                		
                		var oLi = $('<li role="tablink"><a href="javascript:void(0);" data-src="'+base+dc[j].attributes.url+'">'+dc[j].text+'</a></li>');
                	}
                    oDiv.find('.nav-pills').append(oLi);
                    if(dc[j].attributes.url == currHref){
                        oLi.addClass('active');
                        oDiv.find('.panel-title a').attr('aria-expanded','true');
                        oDiv.find('.panel-title .glyphicon').removeClass('glyphicon-menu-right').addClass('glyphicon-menu-down');
                        oDiv.find('.panel-collapse').addClass('in');
                    }
                };
            }else{
                oDiv.find('.panel-collapse').remove();
                oDiv.find('.panel-heading a').removeAttr('data-toggle data-parent aria-expanded aria-controls');
                oDiv.find('.panel-heading a').attr('href','javascript:void(0)').attr('data-id',d[i].id).attr('data-src',base+d[i].attributes.url).addClass('no-children');
            }
        }
        if(jqueryMap.$group.find('li').length!=0&&!jqueryMap.$group.find('li').hasClass('active')){
            var curDiv = jqueryMap.$group.find('.panel').eq(0);
            var curLi = curDiv.find('li').eq(0);
            curLi.addClass('active');
            curDiv.find('.panel-title a').attr('aria-expanded','true');
            curDiv.find('.panel-title .glyphicon').removeClass('glyphicon-menu-right').addClass('glyphicon-menu-down');
            curDiv.find('.panel-collapse').addClass('in');
        }if(jqueryMap.$group.find('li').length==0 && TitleType !=0){
            var curDiv = jqueryMap.$group.find('.panel').eq(0);
            var firstA = curDiv.find('a');
            firstA.trigger('click');
        };
    };
    navExpandToggle = function(){
        if(stateMap.expanded){
            $('.content-main').animate({'left':0},200);
            $('.content-nav').animate({'left':-180},200);
            stateMap.expanded = false;
        }
        else{
            $('.content-main').animate({'left':180},200);
            $('.content-nav').animate({'left':0},200);
            stateMap.expanded = true;
        }
    };
    configModule = function (d) {
        $.extend(stateMap,d);
    };
    init = function($container){
        stateMap.$append_target = $container;
        $container.append(configMap.main_html);
        setJqueryMap($container);
        return this;
    };
    return {
        configModule:configModule,
        init:init
    }
}())

function addHospitalEvent(){
	//获取医院信息
	var yiyuanListHtml =''
	var url4 = host + "/clidoctor/getAllYiyuanInfo";
	var list = JSON.parse($.cookie("parameterArray"))[0].children;
	for(var j=0;j<list.length;j++)
	{
		yiyuanListHtml += '<option value="'+list[j]["id"]+'">'+list[j]["text"]+'</option>'
	}
	$("#hospital").empty().append(yiyuanListHtml);
	$("#hospital").select2();
}
function changeHospitalEvent(){
	yiyuanId = $("#hospital").find("option:selected").val();
	$("#normal_content").load(hostUrl+"/index.jsp");
}
//菜单或按钮权限检查
var authorityArr = [],risReportParam={}; //全局参数 权限按钮
function checkPermission(mid,content,type){
	debugger;
    if(mid) {
    	//var centerUrl = "http://192.168.1.143:8080/centerweb/cloud";
        var url = centerUrl + "/sysUser/initCloudUser";
        $.ajax({
            url: url,
            type: "get",
            dataType: "jsonp",
            data: {
                'userId': userId,
                'loginCode': loginName,
                'modId': mid
            },
            success: function (resp) {
                if (resp) {
                	var allbtn
                	var resultArr = [];
                	for(var i=0;i<resp.length;i++)
                	{
                		resultArr.push(resp[i].btnCode);
                		authorityArr.push(resp[i].btnCode);
                		if(resp[i].sysModUrl){
                			risReportParam[resp[i].btnCode] = (resp[i]);
                		}
                	}
                	if(type=="list"){
                		allbtn=$(content).find(".anthority_list");
                		for (var j=0;j<allbtn.length;j++){
                			var listname = $(allbtn[j]).attr("name");
                			if(listname == "" ||($.inArray(listname,resultArr)>=0)){
                				$(allbtn[j]).show();
                			}else{
                				$(allbtn[j]).hide();
                			}
                		}
                	}else{
                		
                		allbtn=$(content).find("button");
                		var list = $(content).find(".anthority_list");
                		for (var k=0;k<list.length;k++){
                			var listname = $(list[k]).attr("name");
                			if(listname == "" ||($.inArray(listname,resultArr)>=0)){
                				$(list[k]).show();
                			}else{
                				$(list[k]).hide();
                			}
                		}
                		for (var j=0;j<allbtn.length;j++){
                			if(allbtn[j].name == "" ||($.inArray(allbtn[j].name,resultArr)>=0)){
                				$(allbtn[j]).show();
                				if(allbtn[j].name == "jygh"){
                					setJianyiGuahao(true);
                				}
                				if(allbtn[j].name == "indexsk"||allbtn[j].name == "indexsfz"){
                					setIndexShuaka(true,allbtn[j].name);
                				}
                			}else{
                				$(allbtn[j]).hide();
                			}
                		}
                	}
                } else {
                    layer.msg('您无此功能权限！',{time:3000,icon:2,skin: 'layui-layer-msg2'});
                }
            },
            error: function () {
            	layer.msg('与服务器通讯错误',{time:3000,icon:2,skin: 'layui-layer-msg2'});
            }
        });
    }
}
//简易挂号权限单独处理，样式问题
function setJianyiGuahao(type){
	if(type){  //显示
		$("#hujiao").parents(".col-md-10").css("padding","0px 3px");
		$("#hujiao").parents(".col-md-10").removeClass("col-md-10").addClass("col-md-5");
	}else{
		$("#hujiao").parents(".col-md-5").css("padding","0px 3px 0 15px");
		$("#hujiao").parents(".col-md-5").removeClass("col-md-5").addClass("col-md-10");
	}
}
function setIndexShuaka(type,btname){
	var or = false;
	if(btname == 'indexsk'){
		var flag = $("#index_input_btn").find(".indexsfz").is(":visible");
		if(flag){
			or = true;
		}
	}else if(btname == 'indexsfz'){
		var flag = $("#index_input_btn").find(".indexsk").is(":visible");
		if(flag){
			or = true;
		}
	}
	if(or){
		$("#index_input_btn").find(".search-group").removeClass("col-md-9").addClass("col-md-6");
		 $("#index_input_btn").find(".indexsk").css("padding-right","5px")
	}
	if(type){  //显示
		$("#index_input_btn").find(".col-md-12").css("padding-right","5px");
		$("#index_input_btn").find(".col-md-12").removeClass("col-md-12").addClass("col-md-9");
		$("#index_input_btn").find("."+btname).removeClass("hidden");
	}else{
		$("#index_input_btn").find(".col-md-9").css("padding-right","15px");
		$("#index_input_btn").find(".col-md-9").removeClass("col-md-9").addClass("col-md-12");
		$("#index_input_btn").find("."+btname).addClass("hidden");
	}
}
function setIndexInputStyle(){
	$("#index_input_btn").find(".col-md-12").css("padding-right","5px");
	$("#index_input_btn").find(".col-md-12").removeClass("col-md-12").addClass("col-md-7");
	$("#index_input_btn").find(".indexsk").removeClass("hidden");
	$("#index_input_btn").find(".indexsk").css("padding-right","5px");
	$("#index_input_btn").find(".indexsfz").removeClass("hidden");
}

//级菜单当前位置控制001一级菜单 002二级菜单
function refushPosition(listType){
	var html;
	var firstTitle=$("#minMenu").find(".checkMinMenu").text().trim();
	var secondTitle=$("#accordion").find(".active").parents(".panel").find(".panel-title").text().trim();
	var thirdTitle=$("#accordion").find(".active").text().trim();
	html="<li><span>您的当前位置：</span></i>";
	if(listType=='001'){
		if(firstTitle){
			html+="<li><span>"+firstTitle+"</span></i>";
			}
	}else{
		if(firstTitle){
			html+="<li><span>"+firstTitle+"</span></i>";
			}
			if(secondTitle){
				html+="<li><span>"+secondTitle+"</span></i>";
			}
			if(thirdTitle){
				html+="<li><span>"+thirdTitle+"</span></i>";
			}
	}
	
	$("#now_position").empty().append(html);
	//位置高亮
	$("#now_position").find("li:last").addClass("now-position")
}


//点击头部收缩按钮
var headerFlag = true;
function changeHeader(){
	if(headerFlag == true){
		$("header").animate({height:"35px"},100);
		$("#banner .logo").css({transform:"scale(0.7)",top:"-2px"});
		$("#banner").css({height:"35px","line-height":"30px"});
		$("#banner .systemText").css({"font-size":"1.2rem","line-height":"30px",bottom:"20px"});
		$(".header>a").css({"padding":"7px 15px"});
		$(".header>a>span>span").hide();
		$('.container').animate({"top":"35px"},100);
		$("header .left_self").hide();
		headerFlag = false;
	}else{
		$("header").animate({height:"60px"},100);
		$("#banner .logo").css({transform:"scale(1)",top:"12px"});
		$("#banner").css({height:"60px","line-height":"60px"});
		$("#banner .systemText").css({"font-size":"1.5rem","line-height":"60px",bottom:"5px"});
		$(".header>a").css({"padding":"18px 15px"});
		$(".header>a>span>span").show();
		$('.container').animate({"top":"60px"},100);
		$("header .left_self").show();
		headerFlag = true;
	}
}


function logout(){
//	 layer.confirm('您确定要离开云健康吗？', {
//         btn: ['确定','取消'], //按钮
//         icon:3,
//     }, function(){
//         $.cookie('userId', ''); //用户Id
//         $.cookie('loginName', ''); //用户名称
//         $.cookie('trueName', ''); //用户名称
//         $.cookie('orgId', ''); //部门编号
//         $.cookie('loginPwd', ''); //用户密码
//         $.cookie('ip', '');//用户本机ip
//         $.cookie('loginTime','');
//         $.cookie('language','');//默认中文
//         $.cookie('identity','');//0权限过滤，1不过滤权限
//         window.location.href = host;
//     }, function(){
//
//     });

//	var loginName= $.cookie('loginName');
	$.ajax({
		url : kzzxUrl+"/sysUser/cloudLogout",
		data : {"loginName":loginName},
		dataType: "jsonp",
		type : "get",
        crossDomain: true,
        jsonp:"callback",    
        jsonpCallback:"success_jsonp",  
		success : function(data) {
			data = data[0];
			if(data.result=='SUCCESS'){
				window.location.href = host;
				if(fromMain&&"1"==fromMain){
				     window.location.href= $.cookie('unityUrl');
				 }else{
				     window.location.href = base;
				 }
			}
		}
	});
}

function userInfoEvent(){
	laytplUrl(myurl + "/module/userInfo.html",{}, function(data, html) {
		var index = layer.open({
			type : 1,
			// scrollbar : false,
			title : "人员信息",
			area : [ "430px", "290px" ],
			shade : 0.1,
//			 maxmin : true,
			content : html,
			closeBtn : 1,
			success : function() {
//				 var loginName = $.cookie('loginName'); //用户名称
//		            var trueName = $.cookie('trueName'); //用户名称
//		            var orgId = $.cookie('orgId'); //部门编号
//		            var bck03 = $.cookie('bck03'); //科室
		            var loginTime = $.cookie('loginTime');
		            $("#login_name_label").html(loginName);
		            $("#true_name_label").html(trueName);
		            $("#login_orgId_label").html(bck03);
		            $("#login_date_label").html(millisecondsStrToDate(loginTime));

				$(".remove").on("click",function(){
					layer.close(index);
				});
			}
		})

	});
}


//加载所有诊室默认当前诊室
function loadAllClinicsM(){
	var all_clilics="";
	var url = rootUrl + "/clidoctor/querybas02Bybce01";
	var para={bce01:bce01};
	$.when($.get(url, para)).done(function(data) {
		if (data.list.length) {
			for(var i =0;i<data.list.length;i++){
				
				all_clilics +="<option value="+data.list[i].bas01+">"+data.list[i].bas02+"</option>";
			}
			$("#all_clinics").empty().append(all_clilics);
			$("#all_clinics").select2();
			if((localStorage.bas01 && localStorage.bas01!="undefined"&& localStorage.bas01 !="null")&&(bce01==localStorage.bce01)){
				$("#all_clinics").val(localStorage.bas01).trigger("change");
			}else {
				clinicsChose(data.list);
			}
			clinicsChangeEvent();
			
		} 
		
	})
};
function clinicsChose(arr){
	laytplUrl(myurl+"/module/clinicschose.html",{},function(list,html){
		var index = layer.open({
			type : 1,
			scrollbar : false,
			title : "当前诊室选择",
			area : [ "400px", "300px"],
			shade : 0.3,
//			maxmin : true,
			content : html,
			closeBtn:0,
			success : function() {
				 clinicsTableInit(arr);
				 $("#save_clinics").on("click",function(){
					 var selectedId = $("#clinics_table").jqGrid("getGridParam", "selrow");
					 var rowData = $("#clinics_table").jqGrid("getRowData", selectedId);
					 if(selectedId){
						 localStorage.bas02 = rowData.bas02;
						 localStorage.bas01 = rowData.bas01;
						 saveClinicsChose(rowData.bas01,1); //1 表示走的确定按钮，需要关闭弹出层和提示保存成功
						 
					 }else{
						 layer.msg('请选择诊室',
									{
								time : 2000,
								icon : 0,
								skin : 'layui-layer-msg0'
									});
					 }
				 })
				
			}
		})
		
	});
}
function clinicsTableInit(arr) {
	$('#clinics_table_container').resize(function() {
		$("#clinics_table").setGridWidth($("#clinics_table_container").width() * 1);
	});
	jQuery('#clinics_table').GridUnload();
	jQuery("#clinics_table").jqGrid(
					{
//						url : rootUrl + "/triage/queryTriageList",
//						postData : param,
//						mtype : 'get',
						datatype : "local",
						height : 'auto',
						width : "auto",
						data:arr,
						autowidth : true,
						rownumbers : true,
						multiselect:true,
						multiboxonly:true,
						colModel : [ {
							label : '编号',
							name : 'bas01',
							align : "center"
						}, {
							label : '名称',
							name : 'bas02',
							align : "center"
						}, {
							label : '号类',
							name : 'bcb03',
							align : "center"
						}, {
							label : '位置',
							name : 'bas05',
							align : "center"
						}, 
						{
							name : 'bck01',
							hidden : true
						},
//						{
//							name : 'bce01',
//							hidden : true
//						},
						{
							name : 'bck02',
							hidden : true
						} ],
						rowNum : arr.rows,
						onSelectRow : function(rowid, status) {
							
						},
						gridComplete : function() {
						},
						loadComplete : function(data) {
							//无数据的时候展示暂无数据信息
							if (arr.length < 1) {
								var $tr = $('#clinics_table').find(
										'tbody>tr:last');
								var len = $tr.find('td').length;
								$("#clinics_table").html('<tr><td colspan="'+ parseInt(len)+ '" style="text-align:left;">没有符合条件的数据！</td></tr>');
							}
						},
					});
}
function clinicsChangeEvent(){
	localStorage.bas02 = $("#all_clinics").find("option:selected").text();
	localStorage.bas01 = $("#all_clinics").find("option:selected").val();
	localStorage.bce01 = bce01;
	saveClinicsChose(localStorage.bas01);
	
//	var cururl = $("#accordion").find(".active").find("a").attr("data-src");
//	$('#tabContent').load(cururl);

}

function saveClinicsChose(bas01,flag){
	$.ajax({
		url:rootUrl + "/clidoctor/updateBas1_bce1",
		type:"post",
		dataType:"json",
		data:{bas01:bas01,bce01:bce01},
		success:function(data)
		{
			debugger;
			if(flag){
				layer.msg('设置成功',
						{
					time : 2000,
					icon : 1,
					skin : 'layui-layer-msg1'
						});
				$("#all_clinics").val(localStorage.bas01).trigger("change");
				layer.closeAll();
			}
			if (valueArr.p_100_105002_419=="1")
			{
				changeBck1(localStorage.bas01);//更新诊室对应的科室
			}
		}
	});
}

function changeBck1(bas01)
{
	$.ajax({
		url:rootUrl + "/clidoctor/selectDataByScriptId",
		type:"get",
		dataType:"json",
		data:{ID:10000023, paramStr:'{bas01:"'+bas01+'"}'},
		success:function(data)
		{
			if(data && data.list)
			{
				$("#departmentList").find("option[id='"+data.list[0].bck01+"']").attr("selected","selected").trigger("change");
			}
		}
	});
}












